package com.app.internationaltravel.service.impl;

import com.app.internationaltravel.dao.UserDao;
import com.app.internationaltravel.dao.UserDetailDao;
import com.app.internationaltravel.dao.UserGoldDao;
import com.app.internationaltravel.dao.UserSignDao;
import com.app.internationaltravel.entity.UserDetail;
import com.app.internationaltravel.entity.UserGold;
import com.app.internationaltravel.entity.UserSign;
import com.app.internationaltravel.service.intf.UserSignService;
import com.app.internationaltravel.util.DateUtil;
import com.app.internationaltravel.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * @author 刘豆豆
 * @date 2022/12/14
 */
@Service
public class UserSignServiceImpl implements UserSignService {

  @Resource
  private UserSignDao dao;
  @Resource
  private UserDetailDao detailDao;
  @Resource
  private UserGoldDao goldDao;

  @Override
  public R checkSign(int uid) {
    //1.查询用户最后一次签到的数据
    UserSign sign = dao.queryLast(uid);
    //2.验证是否有签到记录
    if (sign!=null){
      //3.计算最后一次签到 距离现在 相差的天数 一次验证今日是否签到
      if (DateUtil.diffDay(sign.getCtime())==0){
        //今日已签到
        return R.fail("今日已签到");
      }
    }
    return R.ok("签到成功");
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public R sign(int uid) {
    UserSign sign = dao.queryLast(uid);
    UserSign userSign = new UserSign(uid,new Random().nextInt(3)+3,0,1);
    if (sign!=null) {
      int i = DateUtil.diffDay(sign.getCtime());
      if (i == 0) {
        return R.fail("亲，今日已签到！");
      }else {
        //今日没签到 可以签到

        //验证是否为连续签到
        if (i==1){
          //连续签到，计算是否给予 额外奖励
          userSign.setDays(sign.getDays()+1);
          //验证连续签到的天数 是否大于等于7
          if (userSign.getDays()>=7){
            //奖励10虚拟币
            userSign.setExagold(10);
          }else if (userSign.getDays()==3){
            //连续签到3天 奖励5虚拟币
            userSign.setExagold(5);
          }
        }
      }
    }
    if (dao.insert(userSign)>0){
      //更改用户虚拟币的数量
        detailDao.updataGold(uid,userSign.getGold()+userSign.getExagold());
      //记录虚拟币的变动
      goldDao.insert(new UserGold(uid, 2,userSign.getGold()+userSign.getExagold(),"签到奖励"));
      return R.ok("今天未签到，可以进行签到");
    }
    return R.fail();
  }

  @Override
  public R queryMonth(int uid) {
    //为 签到日历 准备的 查询本月的签到数据
    return R.ok(dao.queryMonth(uid,DateUtil.getMonth()));
  }

  @Override
  public R queryAll(int uid) {
      return R.ok(dao.selectList(new QueryWrapper<UserSign>().eq("uid",uid)));
  }
}
